package br.com.montezuma.empresarial.controller;

import java.util.List;

import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.montezuma.empresarial.backend.core.DAO;
import br.com.montezuma.empresarial.models.IListagem;
import br.com.montezuma.empresarial.utils.Filtro;
import br.com.montezuma.empresarial.utils.Login;
/**
 * <pre>
 * @author : David Montezuma
 * Purpose : AbstractController, providing common behavior for controller class.
 * Amendment History                                                                
 * Date - Name - Description                              
 * 26/05/2012 - David Montezuma - initial version.
 * 
 * Copyright 2012 Montezuma Software
 * </pre>
 */
@SuppressWarnings("rawtypes")
public abstract class  AbstractController <Model,ModelDAO extends DAO> implements IController<Model>{
	private ModelDAO modelDAO;
	private Result result;
	private Validator validator;
	
	public AbstractController(Result result, ModelDAO modelsDAO,Validator validator) {
		this.modelDAO = modelsDAO;
		this.result = result;
		this.validator = validator;
	}
	
	/**
	 * @return the result
	 */
	public Result getResult() {
		return result;
	}

	/**
	 * @return the validator
	 */
	public Validator getValidator() {
		return validator;
	}
	protected void executeDominios(){}

	@SuppressWarnings("unchecked")
	public void salvar(Model model){
		valide(model);
		
		if (validator.getErrors().size() == 0) {
			this.modelDAO.open();
			this.modelDAO.beginTransaction();
			this.modelDAO.save(model);
			this.modelDAO.commitTransaction();
			this.modelDAO.close();
			this.result.redirectTo(this.getClass()).listar(null);
		}else{
			executeDominios();
			validator.onErrorUsePageOf(this.getClass()).editar(null);
		}
		
		
	}
	
	protected abstract void valide(Model model);
	
	@SuppressWarnings("unchecked")
	public  List<IListagem> listar(Filtro filtro) {
		System.out.println("###########TESTE##############");
		this.modelDAO.open();
		
		@SuppressWarnings("rawtypes")
		List lista = this.modelDAO.findAll();
		this.modelDAO.close();
		
		return lista;

	}
	
	@SuppressWarnings("unchecked")
	public Model editar(Long id) {
		
		this.modelDAO.open();
		Model editing = null;
		if(id != null) {
			editing = (Model) this.modelDAO.findById(id);
			System.out.println("########consultando##############"+editing);
		}
		
		this.modelDAO.close();
		executeDominios();
		return editing;
		
	}
	
	@SuppressWarnings("unchecked")
	public void excluir(Long id) {
		if (id != null) {
			this.modelDAO.open();
			this.modelDAO.beginTransaction();
			this.modelDAO.delete(this.modelDAO.findById(id));
			this.modelDAO.commitTransaction();
		}
		this.result.redirectTo(this.getClass()).listar(null);
	}
}
